#!/usr/bin/perl
# 2014/01/30 Optimized
# 2011/02/06 Make wig file

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if((@ARGV != 6 and @ARGV != 8) or $ARGV[0] eq '--help'){
	my $message = <<"EOF";
Usage : $0 -i [score file] -t [type of calculation] -w [name of wig file] -v [multiply value]
1: normalized substraction
2: -(log P-value)
3: ratio
4: log2 ratio
5: mutliply normalized substraction by -v value
EOF
	die "$message\n";
}
my %opt;
getopts("i:t:w:v:", \%opt);
my $type = $opt{t};
my $FILE_score = $opt{i};
my $FILE_wig = $opt{w};
(my $title = $FILE_wig) =~ s/\..+$//;
if($title =~ m|/(.+)$|){
	$title = $1;
}
my $multiply_value = 200;
if($type == 5){
	if(exists $opt{v}){
		$multiply_value = $opt{v};
	}else{
		die "require -v option value for type 5 output\n";
	}
}


my $fh_out = IO::File->new($FILE_wig, 'w') or die "cannot write $FILE_wig: $!";
$fh_out->print("track type=wiggle_0 name=$title\n");

my $fh_in = IO::File->new("gzip -dc $FILE_score |") or die "cannot open $FILE_score: $!";
my $pre_chr = '';
while($_ = $fh_in->getline()){
	s/\r?\n//;
	if(m/^#/){
		next;
	}
	my ($chr, $pos, $treatment, $control, $substract_nor, $logPval, $fold_change) = split /\t/;

	if($pre_chr ne $chr){
		$fh_out->printf("variableStep chrom=%s span=30\n", $chr);
	}

	if(($pos - 20) % 30 != 0){
		next;
	}


	my $score = 0;
	if($type == 1){
		$score = $substract_nor;
	}elsif($type == 2){
		$score = $logPval * (-1);
	}elsif($type == 3){
		$score = $fold_change;
	}elsif($type == 4){
		$score =log($fold_change) / log(2);
	}elsif($type == 5){
		$score = $substract_nor * $multiply_value;
	}else{
		die "please select appropriate method\n";
	}

	$fh_out->print("$pos\t$score\n");
	$pre_chr = $chr;
}
$fh_in->close();
$fh_out->close();

